<?php

function salt_cache_token($token) {
    setcookie("saltoken", $token, time()+3600); // seconds
}

function salt_get_cached_token() {
    if (isset($_COOKIE["saltoken"]))
        return $_COOKIE["saltoken"];
    else
        return null;
}

function salt_pkg_install($host, $port, $token, $tgt, $pkg) {
    $ch = curl_init("https://$host:$port/");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'X-Auth-Token:' . $token ));
    $data = [
      "client" => "local",
      "tgt" => $tgt,
      "fun" => "pkg.install",
      "kwarg" => ["pkgs" => [$pkg]]
    ];
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function salt_login($host, $port, $user, $pass) {
    $token = salt_get_cached_token();
    if (isset($token))
        return $token;

    $ch = curl_init("https://$host:$port/login");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, '{"username" : "' . $user . '", "password": "' . $pass  .'", "eauth": "pam"}');
  
    $result = curl_exec($ch);
    curl_close($ch);
  
//    print $result;
    $jsonres = json_decode($result, True);
//    var_dump($jsonres);
    $token = $jsonres["return"][0]["token"];

    salt_cache_token($token);

    return $token;
}

function salt_test_ping($host, $port, $token, $target) {
//    print "test_ping: $host $port $token $target";
    $ch = curl_init("https://$host:$port/");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'X-Auth-Token:' . $token ));
    $data = [
      "client" => "local",
      "tgt" => $target,
      "fun" => "test.ping" ];
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  
    $result = curl_exec($ch);
    curl_close($ch);
    $jsonres = json_decode($result, True);
    return $jsonres["return"][0];
}

?>
